package com.wushi.lenovo.asia5b.app_utils.helper;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.net.http.SslError;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;

import com.google.gson.reflect.TypeToken;
import com.mvp.base.BaseAppCompatActivity;
import com.mvp.common.GlobalValue;
import com.mvp.common.LocalManageUtil;
import com.mvp.utils.AppUtil;
import com.mvp.utils.JsonUtil;
import com.mvp.utils.JsonUtils;
import com.mvp.utils.ResString;
import com.mvp.utils.SharedPreferencesUtils;
import com.mvp.utils.ToastUtil;
import com.wushi.lenovo.asia5b.BuildConfig;
import com.wushi.lenovo.asia5b.R;
import com.wushi.lenovo.asia5b.app_config.UserRepository;
import com.wushi.lenovo.asia5b.app_event.MainTabEvent;
import com.wushi.lenovo.asia5b.app_model.h5.H5Bean;
import com.wushi.lenovo.asia5b.app_model.h5.H5FiexedAdBean;
import com.wushi.lenovo.asia5b.app_model.h5.H5GoodBean;
import com.wushi.lenovo.asia5b.app_model.h5.H5GoodsDetailBean;
import com.wushi.lenovo.asia5b.app_model.h5.H5ShareBean;
import com.wushi.lenovo.asia5b.app_model.h5.H5SwipeInfoBean;
import com.wushi.lenovo.asia5b.app_model.h5.H5ThridAppBean;
import com.wushi.lenovo.asia5b.app_model.h5.H5TitleBean;
import com.wushi.lenovo.asia5b.app_model.h5.H5UrlBean;
import com.wushi.lenovo.asia5b.app_model.h5.H5WishBean;
import com.wushi.lenovo.asia5b.app_model.h5.ThirdMallH5Bean;
import com.wushi.lenovo.asia5b.app_model.other.ShareBean;
import com.wushi.lenovo.asia5b.app_model.other.UserInfo;
import com.wushi.lenovo.asia5b.app_ui.good.activity.ThirdMallActivity;
import com.wushi.lenovo.asia5b.app_ui.h5.CategoryActivity;
import com.wushi.lenovo.asia5b.app_ui.h5.GoodsDetailsActivity;
import com.wushi.lenovo.asia5b.app_ui.h5.LocalMallActivity;
import com.wushi.lenovo.asia5b.app_ui.h5.ThirdContentActivity;
import com.wushi.lenovo.asia5b.app_ui.other.activity.MainActivity;
import com.wushi.lenovo.asia5b.app_ui.other.dialog.ShareDialog;
import com.wushi.lenovo.asia5b.app_ui.shopcar.activity.ShopCarActivity;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import static timber.log.Timber.d;

/**
 * Created by zhangyuncai on 2019/4/2.
 */
public class H5Hepler {

    public static <M extends H5Bean> M parseUrl(Activity activity, String param) {
        if (TextUtils.isEmpty(param)) {
            return null;
        }
        H5Bean doX = null;

        try {
            doX = JsonUtils.parserGsonToObject(param, H5Bean.class);
            if (doX == null) {
                return null;
            }
            d("--->>>>>>>>---doX.getDoX():" + doX.getDoX());


            switch (doX.getDoX()) {
                case "finish": {//结束页面
                    activity.finish();
                }
                break;
                case "showLoading": {
                    if (activity instanceof BaseAppCompatActivity) {
                        BaseAppCompatActivity baseAppCompatActivity = (BaseAppCompatActivity) activity;
                        baseAppCompatActivity.showLoadingBar(null);
                    }
                }
                break;
                case "closeLoading": {
                    if (activity instanceof BaseAppCompatActivity) {
                        BaseAppCompatActivity baseAppCompatActivity = (BaseAppCompatActivity) activity;
                        baseAppCompatActivity.dismissLoadingBar("");
                    }
                }
                break;
                case "openGoodsUrl": {  //跳转商品详情,这个是从搜索图片界面跳转过去的
                    d("--->>>>>>>>---跳转商品详情");
                    H5GoodsDetailBean h5Bean = JsonUtils.parserGsonToObject(param, H5GoodsDetailBean.class);
                    if (!TextUtils.isEmpty(h5Bean.getGoods_url())) {
                        String goods_url = h5Bean.getGoods_url();
                        goods_url = H5Hepler.getH5_Url(goods_url);
                        d("--->>>>>>>>---goods_url:" + goods_url);
                        GoodsDetailsActivity.startGoodsDetailsActivity(activity, goods_url);
                    }
                    return (M) h5Bean;
                }
                case "openThirdUrl": {//当首页中的商品id==0的时候,H5会返回一个第三方该商品的地址
                    d("--->>>>>>>>---当商品id==0的时候,跳转里面的网址");
                    H5GoodsDetailBean h5Bean = JsonUtils.parserGsonToObject(param, H5GoodsDetailBean.class);
                    if (!TextUtils.isEmpty(h5Bean.getGoods_url())) {
//                        CategoryActivity.startCategoryActivity(activity, h5Bean.getGoods_url(), "");
                        Uri uri = Uri.parse(h5Bean.getGoods_url());
                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                        activity.startActivity(intent);
                    }
                    return (M) h5Bean;
                }
                case "openUrl": {//判断专属品牌展示
                    d("--->>>>>>>>---判断专属品牌展示");
                    H5UrlBean h5Bean = JsonUtils.parserGsonToObject(param, H5UrlBean.class);
                    CategoryActivity.startCategoryActivity(activity, H5Hepler.getH5_Url(h5Bean.getUrl()), null);
                    return (M) h5Bean;
                }
                case "to_3_part": {//第三方商城
                    d("--->>>>>>>>---第三方商城");
                    ThirdMallH5Bean h5Bean = JsonUtils.parserGsonToObject(param, ThirdMallH5Bean.class);
                    ThirdMallH5Bean.ValBean valBean = h5Bean.getVal();
                    if (TextUtils.equals(valBean.getAction_type(), "shopglobal")) {
                        activity.startActivity(new Intent(activity, ThirdMallActivity.class));
                    } else if (!TextUtils.isEmpty(valBean.getAction_url())) {
                        if (TextUtils.equals(valBean.getAction_type(), "internal")) {//内部打开
                            ThirdContentActivity.startThirdContentActivityForFull(activity, valBean.getAction_url(), null);
                        } else if (TextUtils.equals(valBean.getAction_type(), "external")) {//浏览器打开
                            Uri uri = Uri.parse(valBean.getAction_url());
                            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                            activity.startActivity(intent);
                        }
                    }

                    return (M) h5Bean;
                }
                case "clickSwipe": {//判断轮播图
                    d("--->>>>>>>>---判断轮播图");
                    H5SwipeInfoBean h5Bean = JsonUtils.parserGsonToObject(param, H5SwipeInfoBean.class);
                    H5SwipeInfoBean.SwipeInfoBean swipeInfo = h5Bean.getSwipeInfo();
                    if (swipeInfo != null && !TextUtils.isEmpty(swipeInfo.getAction_url())) {
                        CategoryActivity.startCategoryActivity(activity, swipeInfo.getAction_url(), "");
                    }
                    return (M) h5Bean;
                }
                case "title": {//标题
                    d("--->>>>>>>>---标题");
                    H5TitleBean h5Bean = JsonUtils.parserGsonToObject(param, H5TitleBean.class);
                    if (h5Bean != null) {
                        return (M) h5Bean;
                    }
                }
                break;
                case "buy_0": {//添加购物车
                    d("--->>>>>>>>---添加购物车");
                    H5GoodBean h5GoodBean = JsonUtils.changeGsonToBean(param, H5GoodBean.class);
                    return (M) h5GoodBean;
                }
                case "share": {//分享
                    d("--->>>>>>>>---分享");
                    H5ShareBean h5ShareBean = JsonUtils.changeGsonToBean(param, H5ShareBean.class);
                    if (!TextUtils.isEmpty(h5ShareBean.getUrl())) {
                        ShareBean shareBean = new ShareBean();
                        shareBean.setShareUrl(h5ShareBean.getUrl());
//                        shareBean.setShareUrl("https://www.baidu.com");
//                        shareBean.setShareUrl("https://www.asia6b.com/product/12002");
                        shareBean.setDesc(h5ShareBean.getName());
                        shareBean.setImgUrl(h5ShareBean.getImage());
                        shareBean.setTitle(h5ShareBean.getName());
                        ShareDialog shareDialog = new ShareDialog(activity, shareBean);
                        shareDialog.show();
                    }
                    return (M) h5ShareBean;
                }
                case "collectGoods": {//收藏商品
                    d("--->>>>>>>>---收藏商品");
                    H5WishBean h5WishBean = JsonUtils.changeGsonToBean(param, H5WishBean.class);
                    return (M) h5WishBean;
                }
                case "wish": {//收藏商品
                    d("--->>>>>>>>---收藏商品");
                    H5WishBean h5WishBean = JsonUtils.changeGsonToBean(param, H5WishBean.class);
                    return (M) h5WishBean;
                }
                case "openPicGoodsUrl": {
                    d("--->>>>>>>>---打开图片商品");
                    H5GoodsDetailBean h5Bean = JsonUtils.parserGsonToObject(param, H5GoodsDetailBean.class);
                    return (M) h5Bean;
                }
                case "toHome": {//主页
                    d("--->>>>>>>>---主页");
                    EventBus.getDefault().post(new MainTabEvent(0));
                    activity.startActivity(new Intent(activity, MainActivity.class));
                    activity.finish();
                }
                break;
                case "kefu": {//客服
                    d("--->>>>>>>>---客服");
                    H5UrlBean h5Bean = JsonUtils.parserGsonToObject(param, H5UrlBean.class);
                    CategoryActivity.startCategoryActivity(activity, h5Bean.getUrl(), "");
                    return (M) h5Bean;
                }
                case "openFullUrl": {//打开全地址
                    d("--->>>>>>>>---打开全地址");
                    H5UrlBean h5Bean = JsonUtils.parserGsonToObject(param, H5UrlBean.class);
                    ThirdContentActivity.startThirdContentActivityForFull(activity, h5Bean.getUrl(), null);
                    return (M) h5Bean;
                }
                case "attr_close": {//关闭购物车窗口
                    d("--->>>>>>>>---关闭购物车窗口");
                }
                break;
                case "cart": {//购物车
                    d("--->>>>>>>>---购物车");
                    if (UserRepository.isLogin(activity)) {
//                        EventBus.getDefault().post(new BaseEvents.MainTabEvent(2));
                        activity.startActivity(new Intent(activity, ShopCarActivity.class));
//                        activity.finish();
                    }
                }
                break;
                //    String url="https://www.facebook.com/profile.php?id=1722485538043321";//网页版facebook
                //                    String url="fb://profile/1722485538043321";//app 版facebook
                case "openFacebook": {//打开facebookapp
                    d("--->>>>>>>>---打开facebookapp");
                    H5ThridAppBean h5Bean = JsonUtils.parserGsonToObject(param, H5ThridAppBean.class);
                    String facebookPackage = "com.facebook.katana";
                    if (AppUtil.INSTANCE.isAppInstall(activity, facebookPackage)) {//app 版facebook
                        Uri uri = Uri.parse(h5Bean.getUrl());
                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                        activity.startActivity(intent);
                    } else {//网页版facebook
                        Uri uri = Uri.parse(h5Bean.getSecondUrl());
                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                        activity.startActivity(intent);
                    }

                }
                break;
                case "openWhatsapp": {
                    H5ThridAppBean h5Bean = JsonUtils.parserGsonToObject(param, H5ThridAppBean.class);
                    String whatsappPackage = "com.whatsapp";
                    if (AppUtil.INSTANCE.isAppInstall(activity, whatsappPackage)) {
                        if (TextUtils.equals("2018", h5Bean.getTo())) {
                            //2018 api
                            Intent intent = new Intent(Intent.ACTION_VIEW);
                            intent.setData(Uri.parse(h5Bean.getUrl()));
                            activity.startActivity(intent);
                        } else {
                            //smsto:60109080255
                            Uri uri = Uri.parse(h5Bean.getUrl());    //指定打开phoneNumber发送信息页面
                            Intent sendIntent = new Intent(Intent.ACTION_SENDTO, uri);
                            sendIntent.setPackage(whatsappPackage);//区别别的应用包名
                            activity.startActivity(sendIntent);
                        }
                    } else {
                        ToastUtil.showToast(ResString.get(R.string.not_app));
                        AppUtil.INSTANCE.downloadApp(activity, whatsappPackage);
                    }
                }
                break;
                case "openMessager": {
                    H5ThridAppBean h5Bean = JsonUtils.parserGsonToObject(param, H5ThridAppBean.class);
                    String messagerPackage = "com.facebook.orca";
                    if (AppUtil.INSTANCE.isAppInstall(activity, messagerPackage)) {
                        Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(h5Bean.getUrl()));
                        activity.startActivity(i);
                    } else {
//                        ToastUtil.showToast(ResString.get(R.string.not_app));
//                        AppUtil.INSTANCE.downloadApp(activity, messagerPackage);
                        Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(h5Bean.getSecondUrl()));
                        activity.startActivity(i);
                    }
                }
                break;
                case "openThirdApp": {//吊起第三方APP
//                    https://www.facebook.com/A5BMY/posts/2135582553400282
                    H5ThridAppBean h5Bean = JsonUtils.parserGsonToObject(param, H5ThridAppBean.class);
//                    h5Bean.setUrl("https://www.facebook.com/A5BMY/posts/2135582553400282");
                    if (!TextUtils.isEmpty(h5Bean.getUrl())) {
                        Uri uri = Uri.parse(h5Bean.getUrl());
                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                        if (!TextUtils.isEmpty(h5Bean.getTo())) {
                            if (TextUtils.equals(h5Bean.getTo(), "facebook")) {//如果to==facebook,那么url必须是"https://www.facebook.com/A5BMY/posts/2135582553400282",否则整个吊起APP失败
                                String facebookPackageName = getFullPackageName(activity, "com.facebook.katana");
                                if (!TextUtils.isEmpty(facebookPackageName)) {//没有安装app,就打开网页版,安装了就打开app
                                    intent.setPackage(facebookPackageName);
                                }
                            }
                            try {
                                activity.startActivity(intent);
                            } catch (Exception e) {
                                //跳转第三方App失败了,就用浏览器打开URL
                                e.printStackTrace();
                                uri = Uri.parse(h5Bean.getUrl());
                                intent = new Intent(Intent.ACTION_VIEW, uri);
                                activity.startActivity(intent);
                            }

                        } else {//没有指向性的第三方APP,就用浏览器打开URL
                            activity.startActivity(intent);
                        }
                    }
                }
                break;
                case "open1688": {//本地商城
                    d("--->>>>>>>>---1688");
                    H5UrlBean h5Bean = JsonUtils.parserGsonToObject(param, H5UrlBean.class);
                    String h5BeanUrl = h5Bean.getUrl();
                    if (!TextUtils.isEmpty(h5BeanUrl) && !h5BeanUrl.endsWith("?")) {
                        h5BeanUrl += "?";
                    }
                    String url = H5Hepler.getH5_Url(h5BeanUrl);
                    LocalMallActivity.startLocalMallActivity(activity, url, "");
                    return (M) h5Bean;
                }
                case "fixedAd": {
                    H5FiexedAdBean h5Bean = JsonUtils.parserGsonToObject(param, H5FiexedAdBean.class);
                    if (h5Bean != null && h5Bean.item != null) {
                        String cookie = (String) SharedPreferencesUtils.getData("cookie", "");
                        List<H5FiexedAdBean.FiexedAdItem> list2 = new ArrayList<>();
                        if (!TextUtils.isEmpty(cookie)) {
                            Type type = new TypeToken<List<H5FiexedAdBean.FiexedAdItem>>() {
                            }.getType();
                            List<H5FiexedAdBean.FiexedAdItem> list = JsonUtil.INSTANCE.jsonToAny(cookie, type);
                            if (list != null && list.size() > 0) {
                                list2.addAll(list);
                            }
                        }
                        for (H5FiexedAdBean.FiexedAdItem fiexedAdItem : list2) {
                            //防止有重复的图片
                            if (TextUtils.equals(fiexedAdItem.img, h5Bean.item.img)) {
                                list2.remove(fiexedAdItem);
                                break;
                            }
                        }
                        list2.add(h5Bean.item);
                        String s = JsonUtil.INSTANCE.anyToJson(list2);
                        SharedPreferencesUtils.putData("cookie", s);
                    }
                }
                break;
                default:
                    break;
            }


        } catch (Exception e) {
            e.printStackTrace();
        }


        return (M) doX;
    }

    /**
     * @param suffixUrl 后缀地址,这个后缀地址必须含有  ?
     * @return 完整地址
     */
    public static String getH5_Url(String suffixUrl) {
        if (!suffixUrl.startsWith("/")) {//检测后缀地址中是否以  "/"开头 ,没有就加上去
            suffixUrl = "/" + suffixUrl;
        }
        String h5Url = String.format("%s%s", GlobalValue.H5_Url, suffixUrl);
        h5Url = addAsiaH5Params(h5Url);
        d("--->>>>>>>>---h5Url:" + h5Url);
        return h5Url;
    }

    /**
     * 判断一下是否是H5_Url的地址,是的话需要添加参数
     *
     * @param url
     * @return
     */
    public static String addAsiaH5Params(String url) {
        if (!TextUtils.isEmpty(url)) {//地址不能为空
            if (url.startsWith(GlobalValue.H5_Url)) {//必须是H5_Url根地址
                if (!url.contains("asiaH5=1") && !url.contains("lang") && !url.contains("member_id")) {//不能含有这3个参数,因为本来就是要添加这3个参数的
                    String asiaH5 = getAsiaH5();
                    if (url.endsWith("?")) {//检测后缀地址是否以 "?"结尾 ,没有的话,说明有多个参数
                        url += asiaH5;
                    } else {
                        url += ("&" + asiaH5);
                    }
                }
            }
        }
        return url;
    }

    private static String getAsiaH5() {
        int member_id = 0;
        if (UserRepository.isLogin()) {
            member_id = UserInfo.getMemberId();
        }
        return String.format("asiaH5=1&lang=%s&member_id=%d", LocalManageUtil.getAppLanguage(), member_id);
    }

    private static String getFullPackageName(Activity activity, String packageName) {
        Intent intent = new Intent(android.content.Intent.ACTION_SEND);
        intent.setType("text/plain");
        List<ResolveInfo> resInfo = activity.getPackageManager().queryIntentActivities(
                intent, 0);
        if (!resInfo.isEmpty()) {
            for (ResolveInfo info : resInfo) {
                if (info.activityInfo.packageName.toLowerCase().contains(
                        packageName)
                        || info.activityInfo.name.toLowerCase().contains(
                        packageName)) {
                    return info.activityInfo.packageName;
                }
            }
        }
        return null;
    }

    public static void alterSSL(Activity activity, WebView view, SslErrorHandler handler, SslError error) {
        if (BuildConfig.DEBUG || (BuildConfig.appType == 0)) {
            handler.proceed();
        } else {
            final AlertDialog.Builder builder = new AlertDialog.Builder
                    (activity);
            builder.setMessage(R.string.ssl_notice);
            builder.setPositiveButton(R.string.picker_sure, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    handler.proceed();
                }
            });
            builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    handler.cancel();
                }
            });
            final AlertDialog dialog = builder.create();
            dialog.show();
//            handler.proceed();
        }
    }
}
